package com.sxt.test;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.factory.HibernateSessionFactory;
import com.sxt.entity.User;

public class Demo1 {
	/**
	 * 添加数据
	 */
	@Test
	public void test1() {
		// 读取并解析配置文件
		 Configuration conf = new Configuration().configure();
		//Configuration conf = new Configuration().configure("/hibernate.xml"); // 自定义xml配置文件
		
		// Configuration conf = new Configuration(); 
		//conf.addClass("xxx.xxx.Xxx");  //用hibernate.properties文件

		// 读取并解析映射信息，创建SessionFactory
		SessionFactory factory = conf.buildSessionFactory();

		// 打开Session
		Session session = factory.openSession();

		// 开始一个事务
		Transaction tx = session.beginTransaction();

		// 数据库操作
		User user = new User("王五", 20, "江西省赣州市", new Date());
		System.out.println(user);
		session.save(user);

		// 提交事务
		tx.commit();

		// 关闭Session
		session.close();
	}

	/**
	 * 删除数据
	 */
	@Test
	public void test2() {
		Configuration conf = new Configuration().configure();
		SessionFactory factory = conf.buildSessionFactory();
		Session session = factory.openSession();
		User user = (User) session.get(User.class, 1);
		Transaction tx = session.beginTransaction();
		session.delete(user);
		tx.commit();
		session.close();
	}
	
	/**
	 * 查询数据
	 */
	@Test
	public void test3() {
		Session session = HibernateSessionFactory.getSession();
		Query query = session.createQuery("from User");
		@SuppressWarnings("unchecked")
		List<User> list =  query.list();
		for (User user : list) {
			System.out.println(user.getUname() + "<-->" + user.getAddress());
		}
		HibernateSessionFactory.closeSession();
	}
}
